package com.yricky.nep.mm;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;

import com.yricky.nep.mm.databinding.ActivityMmnxtfitBinding;

public class MMNextFitActivity extends Activity {
    private ActivityMmnxtfitBinding binding;
    private int mmSize;
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityMmnxtfitBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());
        binding.table.setText(mmInit(mmSize=1024));
        binding.usage.setUsage(mmGetUsage());
        binding.alloc.setOnClickListener((v)->{
            String sizeStr=binding.allocSize.getText().toString();
            int size;
            try{
                size=Integer.parseInt(sizeStr);
                binding.table.setText(mmAlloc(size));
                binding.usage.setUsage(mmGetUsage());
            }catch (Exception e){
                binding.allocSize.setText("");
            }
        });
        binding.free.setOnClickListener(v -> {
            String sizeStr=binding.freeSize.getText().toString();
            String offsetStr=binding.freeOffset.getText().toString();
            int size;
            int offset;
            try{
                size=Integer.parseInt(sizeStr);
                offset=Integer.parseInt(offsetStr);
                binding.table.setText(mmFree(offset,size));
                binding.usage.setUsage(mmGetUsage());
            }catch (Exception e){
                binding.freeSize.setText("");
                binding.freeOffset.setText("");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mmRelease();
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String mmInit(int size);
    public native void mmRelease();
    public native String mmAlloc(int size);
    public native String mmFree(int addrOffset,int size);
    public native String mmGetUsage();
}
